import time
import ctypes
# 进程工具模块
import psutil
# pywin32模块(win32函数接口)
import win32gui
# import win32con
# import win32api
import json
import codecs

# 根据名称查找进程id
def get_pid(pname):
  for proc in psutil.process_iter():
    #print('pid-%d,name:%s' % (proc.pid,proc.name()))
    if proc.name() == pname:
      return proc.pid

# 最小化控制台窗口
def MinimizeConsole():
  # 最小化
  # https://zhidao.baidu.com/question/1802921434194301027.html
  ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 6)

# win10系统win32gui.GetWindowRect()不准确的解决方法
def FixWindowRectProblem():
  # https://stackoverflow.com/questions/40869982/dpi-scaling-level-affecting-win32gui-getwindowrect-in-python
  # Make program aware of DPI scaling
  ctypes.windll.user32.SetProcessDPIAware()

# 回调函数
def _main_callback(hwnd, extra):
  windows = extra
  # 窗口类名
  clsname = win32gui.GetClassName(hwnd)
  # 窗口标题
  title = win32gui.GetWindowText(hwnd)
  # 如果类名为XTPMainFrame,且标题以MVIS开头,则认为找到了MVIS窗口
  if clsname == windows['classname'] and title.startswith(windows['title']):
    windows['hwnd'] = hwnd
  
# 根据窗口的类名和标题开头的几个字母, 查找窗口句柄
def _find_main_window(mainWndClassName, mainWndTitle):
  windows = {
    'classname':mainWndClassName,
    'title':mainWndTitle
  }
  win32gui.EnumWindows(_main_callback, windows)
  # 返回窗口句柄
  return windows['hwnd'] if 'hwnd' in windows else 0

# 回调函数
def _child_callback(hwnd, extra):
  windows = extra
  # 窗口类名
  clsname = win32gui.GetClassName(hwnd)
  if clsname == windows['classname']:
      windows['hwnd'] = hwnd

# 查找属性框句柄
def _find_child_window(parent, childWndClassName):
  if not parent:return
  windows = { 
    'classname': childWndClassName
  }
  win32gui.EnumChildWindows(parent, _child_callback,  windows)
  # 返回窗口句柄
  return windows['hwnd'] if 'hwnd' in windows else 0   

# 获取子窗口矩形
# mainWndClassName      -- 主窗口类名
# mainWndTitle          -- 主窗口标题
# childWndClassName     -- 子窗口类名
def GetChildWndRect(mainWndClassName, mainWndTitle, childWndClassName):
  # print('MVIS进程ID:', get_pid('MVIS.exe'))
  
  # 1、查找主窗口句柄
  parent_hwnd = _find_main_window(mainWndClassName, mainWndTitle)
  if parent_hwnd == 0:
    print('查找指定窗口失败! 类名:', mainWndClassName, '标题:', mainWndTitle)
    return None
    
  print('主窗口句柄:', parent_hwnd, '类名:', mainWndClassName, '标题:', mainWndTitle)

  # 2、查找子窗口句柄
  child_hwnd = _find_child_window(parent_hwnd, childWndClassName)
  if child_hwnd == 0:
    print('查找指定子窗口失败! 父窗口句柄:', parent_hwnd, '类名:', childWndClassName)
    return None
    
  print('子窗口句柄:', child_hwnd, '父窗口句柄:', parent_hwnd, '类名:', childWndClassName)

  # 3、获取主窗口矩形
  print('主窗口矩形:', win32gui.GetWindowRect(parent_hwnd))
  
  # 4、获取子窗口矩形
  left, top, right, bottom = win32gui.GetWindowRect(child_hwnd)
  print('子窗口矩形:', left, top, right, bottom, '宽:', right-left, '高:', bottom-top)

  # 5、返回计算结果
  return (left, top, right, bottom)

# Python2 JSON.load成Unicode的坑
# https://segmentfault.com/a/1190000002779638
def byteify(input, encoding='utf-8'):
  if isinstance(input, dict):
    return {byteify(key):byteify(value) for key,value in input.items()}
  elif isinstance(input, list):
    return [byteify(element) for element in input]
  elif isinstance(input, unicode):
    return input.encode(encoding)
  else:
    return input

# 读取json格式的配置文件
def ReadJsonFile(filename):
  # 读取json配置文件
  with codecs.open(filename, 'r', 'utf8') as f:
    return json.loads(f.read())